/** 
 * @Project ZmkmUserSdk
 * @Filename ZMKMUSER_HttpUtils.java 
 * @Package com.wifiunion.zmkm.utils 
 * @Description TODO 
 * @Author wifiunion
 * @Creation 2016年1月25日 下午2:32:08 
 * @Modification 2016年1月25日 下午2:32:08    
 * @Copyright Copyright © 2012 - 2016 wifiunion.All Rights Reserved.
 **/
package com.wifiunion.zmkm.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.wifiunion.zmkm.entity.AddressInfoEntity;
//import com.wifiunion.zmkm.entity.CertEntity;
import com.wifiunion.zmkm.entity.User;
import com.wifiunion.zmkm.entity.UserAddressEntity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

/**
 * @ClassName ZMKMUSER_HttpUtils
 * @Description TODO
 * @Version 1.0
 * @Author wifiunion
 * @Creation 2016年1月25日 下午2:32:08
 * @Modification 2016年1月25日 下午2:32:08
 **/
public class ZMKMUSER_HttpUtils {
	// private HttpParams httpParams;
	private static HttpClient httpClient;

	public final static String HTTP_SUCCESS = "http_success";
	public final static String HTTP_FAILED = "http_failed";
	public final static String HTTP_NETERROR = "http_neterror";

	public final static int HTTP_NETERROR_CODE = 2;
	public final static int HTTP_SERVERFAILED_CODE = 3;
	public final static int HTTP_SUCCESS_CODE = 1;

//	public static Context mctx;

	private static String doGet(String url, Map params) {
		/* 建立HTTPGet对象 */
		String paramStr = "";
		String authtoken = "";
		if (params.containsKey("Authorization")) {
			// 添加Authorization
			authtoken = (String) params.get("Authorization");
			params.remove("Authorization");
		}
		
		Iterator iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			paramStr += paramStr = "&" + key + "=" + val;
		}
		if (!paramStr.equals("")) {
			paramStr = paramStr.replaceFirst("&", "?");
			url += paramStr;
		}
		HttpGet httpRequest = new HttpGet(url);

		if (!TextUtils.isEmpty(authtoken)) {
			httpRequest.addHeader("Authorization", authtoken);
		}

		String strResult = "";
		try {
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = getHttpClient().execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				String httpResponseStr = EntityUtils.toString(httpResponse.getEntity());
				strResult = parserResult(httpResponseStr);
			} else {
				strResult = HTTP_NETERROR;
			}
		} catch (ClientProtocolException e) {
			// strResult = e.getMessage().toString();
			strResult = HTTP_NETERROR;
			e.printStackTrace();
		} catch (IOException e) {
			// strResult = e.getMessage().toString();
			strResult = HTTP_NETERROR;
			e.printStackTrace();
		} catch (Exception e) {
			// strResult = e.getMessage().toString();
			strResult = HTTP_NETERROR;
			e.printStackTrace();
		}
		// Log.v("strResult", strResult);
		return strResult;
	}

	private String doPost(String url, List<NameValuePair> params) {
		/* 建立HTTPPost对象 */
		HttpPost httpRequest = new HttpPost(url);
		String strResult = "doPostError";
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = getHttpClient().execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				strResult = EntityUtils.toString(httpResponse.getEntity());
			} else {
				strResult = "Error Response: " + httpResponse.getStatusLine().toString();
			}
		} catch (ClientProtocolException e) {
			strResult = e.getMessage().toString();
			e.printStackTrace();
		} catch (IOException e) {
			strResult = e.getMessage().toString();
			e.printStackTrace();
		} catch (Exception e) {
			strResult = e.getMessage().toString();
			e.printStackTrace();
		}
		Log.v("strResult", strResult);
		return strResult;
	}

	// public HttpClient getHttpClient() {
	// // 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）
	// this.httpParams = new BasicHttpParams();
	// // 设置连接超时和 Socket 超时，以及 Socket 缓存大小
	// HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
	// HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
	// HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
	// // 设置重定向，缺省为 true
	// HttpClientParams.setRedirecting(httpParams, true);
	// // 设置 user agent
	// String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN;
	// rv:1.9.2) Gecko/20100115 Firefox/3.6";
	// HttpProtocolParams.setUserAgent(httpParams, userAgent);
	// // 创建一个 HttpClient 实例
	// // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient
	// // 中的用法，在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient
	// httpClient = new DefaultHttpClient(httpParams);
	// return httpClient;
	// }

	private static synchronized HttpClient getHttpClient() {
		if (httpClient == null) {
			final HttpParams httpParams = new BasicHttpParams();

			// timeout: get connections from connection pool
			ConnManagerParams.setTimeout(httpParams, 1000);
			// timeout: connect to the server
			HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
			// timeout: transfer data from server
			HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

			// set max connections per host
			ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(2));
			// set max total connections
			ConnManagerParams.setMaxTotalConnections(httpParams, 20);

			// use expect-continue handshake
			HttpProtocolParams.setUseExpectContinue(httpParams, true);
			// disable stale check
			HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

			HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);

			HttpClientParams.setRedirecting(httpParams, false);

			// set user agent
			// String userAgent =
			// "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2)
			// Gecko/20100115 Firefox/3.6";
			//
			// HttpProtocolParams.setUserAgent(httpParams, userAgent);

			// disable Nagle algorithm
			HttpConnectionParams.setTcpNoDelay(httpParams, true);

			HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

			// scheme: http and https
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

			ClientConnectionManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
			httpClient = new DefaultHttpClient(manager, httpParams);
		}

		return httpClient;
	}

	public static void CertRequest(final Context context, final String fmuuid, final Handler handler) {
		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				String authtoken = ZMKMUSER_SharePUtils.getSharedPreferences(ZMKMUSER_Constant.CONFIG_AUTHTOKEN,
						context);
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("Authorization", authtoken);
				map.put("fmUuid", fmuuid);
				String str = doGet(ZMKMUSER_Constant.SERVER_IP + ZMKMUSER_Constant.HTTP_URL_CERT, map);
				return str;
			}

			@Override
			protected void onPostExecute(String result) {
				try {
					if (ZMKMUSER_HttpUtils.HTTP_NETERROR.equals(result)) {
						Message msg = handler.obtainMessage();
						msg.what = HTTP_NETERROR_CODE;
						handler.sendMessage(msg);
					}
					else if(ZMKMUSER_HttpUtils.HTTP_FAILED.equals(result))
					{
						Message msg = handler.obtainMessage();
						msg.what = HTTP_SERVERFAILED_CODE;
						handler.sendMessage(msg);
					}
					else {
						int isUsed = parserCertSuccessJson(result);
						if(isUsed==0)
						{
							Message msg = handler.obtainMessage();
							msg.what = HTTP_SERVERFAILED_CODE;
							handler.sendMessage(msg);
						}
						else
						{
							Message msg = handler.obtainMessage();
							msg.what = HTTP_SUCCESS_CODE;
							msg.obj = ZMKMUSER_BitmapUtils.getQrCodeBitmap(context, fmuuid);
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = HTTP_NETERROR_CODE;
					handler.sendMessage(msg);
				}
				
			}

		}.execute();
	}
	
	
	public static void qrCodeRequest(final Context context, final String fmuuid, final Handler handler) {
		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				String authtoken = ZMKMUSER_SharePUtils.getSharedPreferences(ZMKMUSER_Constant.CONFIG_AUTHTOKEN,
						context);
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("Authorization", authtoken);
				map.put("fmUuid", fmuuid);
				String str = doGet(ZMKMUSER_Constant.SERVER_IP + ZMKMUSER_Constant.HTTP_URL_AUTH, map);
				return str;
			}

			@Override
			protected void onPostExecute(String result) {
				CertRequest(context, fmuuid, handler);
			}

		}.execute();
	}
	
	

	public static void LoginRequest(final Context context, final String userName, String password,
			final Handler handler) {

		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
//				mctx = context;
				String appid = ZMKMUSER_SharePUtils.getSharedPreferences(ZMKMUSER_Constant.CONFIG_APPID, context);
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("phone", userName);
				map.put("companyCode", appid);
				String str = doGet(ZMKMUSER_Constant.SERVER_IP + ZMKMUSER_Constant.HTTP_URL_LOGIN, map);
				return str;
			}

			@Override
			protected void onPostExecute(String result) {
				try {
					if (ZMKMUSER_HttpUtils.HTTP_NETERROR.equals(result)) {
						Message msg = Message.obtain();
						msg.what = ZMKMUSER_HttpUtils.HTTP_NETERROR_CODE;
						msg.obj = gotFailedJson();
						handler.sendMessage(msg);
					} else {

						Message msg = Message.obtain();
						msg.what = ZMKMUSER_HttpUtils.HTTP_SUCCESS_CODE;
						msg.obj = gotSuccessJson(result,context);
						handler.sendMessage(msg);

						User user = getUserData(result);
						ZMKMUSER_CommonUtils.saveObject(context, ZMKMUSER_Constant.CONFIG_USER, user);
						ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_PHONE, userName, context);
					}
				} catch (Exception e) {
					if (handler != null) {
						Message msg = Message.obtain();
						msg.what = ZMKMUSER_HttpUtils.HTTP_NETERROR_CODE;
						msg.obj = gotFailedJson();
						handler.sendMessage(msg);
					}
					Log.e("zmkmsdk", e.getMessage());
				}
			}

		}.execute();
	}

	/**
	 * 生成成功的json
	 * 
	 * @return
	 */
	private  static String gotSuccessJson(String jsonStr,Context context) {

		String result = "";
		JSONObject successJson = new JSONObject();
		try {
			JSONObject jobj = new JSONObject(jsonStr);
			JSONObject jDataObj = jobj.getJSONObject("data");

			JSONArray jAddressArray = jDataObj.getJSONArray("addresses");
			String authtoken = jDataObj.getString("authtoken");
			if(!TextUtils.isEmpty(authtoken))
			{
				ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_AUTHTOKEN, authtoken, context);
			}
			JSONArray array = new JSONArray();
			for (int i = 0; i < jAddressArray.length(); i++) {
				JSONObject jSubObj = (JSONObject) jAddressArray.get(i);
				AddressInfoEntity ad = new AddressInfoEntity();

				JSONObject jnewobj = new JSONObject();
				jnewobj.put("fmUuid", jSubObj.getString("fmUuid"));
				jnewobj.put("province", jSubObj.getString("province"));
				jnewobj.put("city", jSubObj.getString("city"));
				jnewobj.put("area", jSubObj.getString("area"));
				jnewobj.put("communityName", jSubObj.getString("communityName"));
				jnewobj.put("segmentName", jSubObj.getString("segmentName"));
				jnewobj.put("buildingName", jSubObj.getString("buildingName"));
				jnewobj.put("unitName", jSubObj.getString("unitName"));
				jnewobj.put("roomName", jSubObj.getString("roomName"));
				array.put(jnewobj);
			}
			successJson.put("result", 1);
			successJson.put("message", "");
			successJson.put("AddressInfo", array);
			result = successJson.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			result = gotFailedJson();
		}
		return result;
	}

	/**
	 * 生成失败的json
	 * 
	 * @return
	 */
	private static String gotFailedJson() {
		JSONObject failedJson = new JSONObject();
		try {
			failedJson.put("result", 2);
			failedJson.put("message", HTTP_NETERROR);
			JSONArray addressarray = new JSONArray();
			failedJson.put("AddressInfo", addressarray);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return failedJson.toString();
	}

	/**
	 * 
	 * @Name parserJson
	 * @Description 解析返回的数据
	 * @param str
	 * @return
	 * @return String
	 * @Author wifiunion
	 * @Date 2016年1月29日 上午10:00:12
	 * 
	 */
	private static String parserResult(String jsonstr) {
		String parserResult = "";
		try {

			JSONObject jsonObj = new JSONObject(jsonstr);
			int result = jsonObj.getInt("result");
			switch (result) {
			case 0:
				parserResult = HTTP_FAILED;
				break;
			case 1:
				parserResult = jsonstr;
				break;
			}
		} catch (JSONException e) {
			e.printStackTrace();
			parserResult = HTTP_NETERROR;
		}
		return parserResult;
	}

	/**
	 * 生成成功的json
	 * 
	 * @return
	 */
	private static int parserCertSuccessJson(String jsonStr) {

		int result = 0;
		try {
			JSONObject jobj = new JSONObject(jsonStr);

			if (jobj.has("data")) {

				JSONObject certjson = jobj.getJSONObject("data");
				int isUsed = certjson.getInt("isUsed");
				if (isUsed == 1) {
					result = isUsed;
				} else {
					result = 0;
				}
			} else {
				result = 0;
			}

		} catch (JSONException e) {
			e.printStackTrace();
			result = 0;
		}
		return result;
	}

	private static User getUserData(String jsonStr) {

		User user = new User();

		try {
			JSONObject jobj = new JSONObject(jsonStr);

			JSONObject jDataObj = jobj.getJSONObject("data");

			user.setId(jDataObj.getString("id"));
			/**
			 * 设置uuid
			 */
			user.setUuid(jDataObj.getString("uuid"));
			/**
			 * 用户身份
			 */
			user.setAuthtoken(jDataObj.getString("authtoken"));
			/**
			 * 图片服务器地址
			 */
			user.setImageServer(jDataObj.getString("imageServer"));
			/**
			 * 头像地址
			 */
			user.setPicurl(jDataObj.getString("picurl"));
			/**
			 * 是否是业主 0:不是 1:是
			 */
			user.setIsOwner(jDataObj.getInt("isOwner"));
			/**
			 * 视频sip账号
			 */
			user.setSip(jDataObj.getString("sip"));
			/**
			 * 视频sip账号密码
			 */
			user.setSipPwd(jDataObj.getString("sipPwd"));
			/**
			 * 视频子账户Id
			 */
			user.setSubAccountSid(jDataObj.getString("subAccountSid"));
			/**
			 * 视频子账户的授权令牌
			 */
			user.setSubToken(jDataObj.getString("subToken"));
			/**
			 * 是否显示房产别名,0不显示,1显示
			 */
			user.setIsShowAlias(jDataObj.getInt("isShowAlias"));
			/**
			 * 最后登录时间
			 */
			user.setLastTime(jDataObj.getString("lastTime"));

			user.setIsHasSecurityAnswer(jDataObj.getInt("isHasSecurityAnswer"));

			LinkedList<UserAddressEntity> addressList = new LinkedList<UserAddressEntity>();

			JSONArray jAddressArray = jDataObj.getJSONArray("addresses");

			for (int i = 0; i < jAddressArray.length(); i++) {

				JSONObject jSubObj = (JSONObject) jAddressArray.get(i);

				UserAddressEntity address = new UserAddressEntity();

				address.setProvince(jSubObj.getString("province"));

				address.setCity(jSubObj.getString("city"));

				address.setArea(jSubObj.getString("area"));

				address.setAddress(jSubObj.getString("address"));

				address.setCommunityName(jSubObj.getString("communityName"));

				address.setSegmentName(jSubObj.getString("segmentName"));

				address.setBuildingName(jSubObj.getString("buildingName"));

				address.setUnitName(jSubObj.getString("unitName"));

				address.setRoomName(jSubObj.getString("roomName"));

				address.setFmUuid(jSubObj.getString("fmUuid"));

				address.setCommunityUuid(jSubObj.getString("communityUuid"));

				address.setB(jSubObj.getString("b"));

				address.setF(jSubObj.getString("f"));

				address.setR(jSubObj.getString("r"));

				address.setM(jSubObj.getString("m"));

				address.setN(jSubObj.getString("n"));

				address.setD(jSubObj.getString("d"));

				address.setSip(jSubObj.getString("sip"));

				address.setSipPwd(jSubObj.getString("sipPwd"));

				address.setS_sip(jSubObj.getString("s_sip"));

				address.setS_sipPwd(jSubObj.getString("s_sipPwd"));

				address.setB_sip(jSubObj.getString("b_sip"));

				address.setB_sipPwd(jSubObj.getString("b_sipPwd"));

				address.setU_sip(jSubObj.getString("u_sip"));

				address.setU_sipPwd(jSubObj.getString("u_sipPwd"));

				address.setAlias(jSubObj.getString("alias"));

				address.setSegmentUuid(jSubObj.getString("segmentUuid"));

				address.setBuildingUuid(jSubObj.getString("buildingUuid"));

				address.setUnitUuid(jSubObj.getString("unitUuid"));

				address.setS_doorControl(jSubObj.getInt("s_doorControl"));

				address.setS_doorControlType(jSubObj.getInt("s_doorControlType"));

				address.setB_doorControl(jSubObj.getInt("b_doorControl"));

				address.setB_doorControlType(jSubObj.getInt("b_doorControlType"));

				address.setU_doorControl(jSubObj.getInt("u_doorControlType"));

				address.setU_doorControlType(jSubObj.getInt("u_doorControlType"));

				address.setTime(jSubObj.getInt("time"));
				
				addressList.add(address);
			}
			user.setAddresses(addressList);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return user;
	}

//	public CertEntity getCert(String certJson) {
//		CertEntity cert = new CertEntity();
//		try {
//			JSONObject json = new JSONObject(certJson);
//			cert.setEndTime(json.getLong("endTime"));
//			cert.setStartTime(json.getLong("startTime"));
//			cert.setIsUsed(json.getInt("isUsed"));
//		} catch (Exception e) {
//
//		}
//		return cert;
//	}

	public static void registerApp(Context ctx, String appid) {
		ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_APPID, appid, ctx);
	}

	/**
	 * 
	 * @Name logout
	 * @Description sdk 登出，清空数据
	 * @param context
	 * @return void
	 * @Author wifiunion
	 * @Date 2016年1月29日 下午3:03:15
	 *
	 */
	public static void logout(Context context) {
		ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_APPID, "", context);
		ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_USER, "", context);
		ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_PHONE, "", context);
		ZMKMUSER_SharePUtils.setSharedPreferences(ZMKMUSER_Constant.CONFIG_AUTHTOKEN, "", context);
	}
}
